package com.copa.l206;

import java.util.Stack;

/**
 * @author copa
 * @createDate 2022-05-23 16:28
 * @function 迭代法
 */
public class Test1 {

    public ListNode reverseList(ListNode head) {
        // 详解看title.txt，关于各个指针的变换
        ListNode dummy = new ListNode();
        dummy.next = head;
        while (head != null && head.next != null) {
            ListNode temp = dummy.next;
            ListNode next = head.next;
            head.next = head.next.next;
            dummy.next = next;
            next.next = temp;
        }
        return dummy.next;
    }
    // 下面是我第一时间想出来的，利用栈的特性
//    public ListNode reverseList(ListNode head) {
//        if (head == null) {
//            return head;
//        }
//        Stack<Integer> stack = new Stack<>();
//        while (head != null) {
//            stack.push(head.val);
//            head = head.next;
//        }
//        head = new ListNode(stack.pop());
//        ListNode temp = head;
//        while (stack.size() > 0) {
//            temp.next = new ListNode(stack.pop());
//            temp = temp.next;
//        }
//        return head;
//    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode result = new Test1().reverseList(head);
        while (result != null) {
            System.out.print(result.val + "\t");
            result = result.next;
        }
    }
}
